<template>
  <div>
    <a-form
        :label-col="{ style: { width: '80px' } }"
        :model="notice"
        :rules="rules"
        labelAlign="right"
        ref="noticeFrom"
    >
      <a-form-item label="标题" name="title">
        <a-input v-model:value="notice.title" placeholder="请输入标题" />
      </a-form-item>
      <a-form-item label="内容">
        <div ref="editorRef" style="height: 480px;width: 100%" />
      </a-form-item>
      <a-form-item label="通知类型">
        <a-select
            v-model:value="notice.type"
        >
          <a-select-option :value="0">系统通知</a-select-option>
          <a-select-option :value="1">用户通知</a-select-option>
          <a-select-option :value="2">法律文献</a-select-option>
        </a-select>
      </a-form-item>
    </a-form>
    <a-space class="functionBox">
      <a-button @click="cancel">取消</a-button>
      <a-button type="primary" @click="submit(0)">保存操作</a-button>
      <a-button type="primary" danger @click="submit(1)">立即发布</a-button>
    </a-space>
  </div>
</template>

<script setup lang="ts">
    import { ref, onMounted, onUnmounted, getCurrentInstance } from "vue";
    import type { Notice } from "@/interface/Notice"
    import {AiEditor} from "aieditor";
    import "aieditor/dist/style.css";
    import { useLoginStore } from "@/stores/loginStore"

    interface Props {
      notice: Notice;
    }

    let param  = withDefaults(defineProps<Props>(),{})

    let notice = ref({
      type: 0
    } as Notice);

    let loginStore = useLoginStore();

    let { proxy } = getCurrentInstance() as any;

    let noticeFrom = ref();
    let rules = {
      title: [
        { required: true, message: "请输入标题", trigger: "blur" },
      ],
      content: [
        { required: true, message: "请输入内容", trigger: "blur" },
      ],
    };

    let editorRef = ref();
    let aiEditor: AiEditor | null = null;
    onMounted(() => {
      aiEditor = new AiEditor({
        element: editorRef.value as Element,
        placeholder: "点击输入内容...",
        content: '',
        image: {
          allowBase64: true,
          defaultSize: 350,
          uploadUrl: proxy.UploadUrl,
          uploadHeaders: {
            "Auth": loginStore.loginInfo.token
          },
          uploader: (file: File, uploadUrl: string, headers: Record<string, any>, formName: string): Promise<Record<string, any>> => {
            const formData = new FormData();
            formData.append("file", file);
            return new Promise((resolve, reject) => {
              fetch(uploadUrl, {
                method: "post",
                headers: {'Accept': 'application/json', ...headers},
                body: formData,
              }).then((resp) => resp.json())
                  .then(json => {
                    if (json.code == 200) {
                      let res = {} as any;
                      res.errorCode = 0;
                      res.data = {
                        src: proxy.PicPrefixUrl + json.data,
                        alt: file.name,
                      }
                      resolve(res);
                    }
                  }).catch((error) => {
                reject(error);
              })
            });
          }
        },
        attachment: {
          uploadUrl: proxy.UploadUrl,
          uploadHeaders: ()=>{
            return {
              "Auth": loginStore.loginInfo.token
            }
          },
          uploader: (file: File, uploadUrl: string, headers: Record<string, any>, formName: string): Promise<Record<string, any>> => {
            const formData = new FormData();
            formData.append("file", file);
            return new Promise((resolve, reject) => {
              fetch(uploadUrl, {
                method: "post",
                headers: {'Accept': 'application/json', ...headers},
                body: formData,
              }).then((resp) => resp.json())
                  .then(json => {
                    if (json.code == 200) {
                      let res = {} as any;
                      res.errorCode = 0;
                      res.data = {
                        href: proxy.PicPrefixUrl + json.data,
                        fileName: file.name,
                      }
                      resolve(res);
                    }
                  }).catch((error) => {
                reject(error);
              })
            });
          }
        },
      });
      if (param.notice) {
        notice.value = param.notice;
        aiEditor.setContent(param.notice.content);
      }
    })

    let emiter = defineEmits(['sendNotice','cancelNotice']);

    function cancel() {
      emiter('cancelNotice', true);
      notice.value = {
        type: 0
      } as Notice;
    }

    function submit(status : number = 0) {
      noticeFrom.value.validate().then(() => {
        if (aiEditor) {
          notice.value.status = status;
          if (status == 1) {
            notice.value.publishDate = new Date().valueOf().toString();
          }
          notice.value.content = aiEditor.getHtml();
          emiter('sendNotice', notice.value);
        }
      }).catch( (res : any) => {
        console.log(res);
      });
    }

    onUnmounted(() => {
      aiEditor && aiEditor.destroy();
    });

</script>

<style scoped lang="scss">
    .functionBox {
      display: flex;
      justify-content: end;
    }
</style>
